﻿using System;
using System.Linq;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Core.Service;

namespace Icms.Service
{
    public class HearingService : CrudService<Hearing>, IHearingService
    {
        private readonly IUniRepo ur;

        public HearingService(IRepo<Hearing> repo, IUniRepo ur)
            : base(repo)
        {
            this.ur = ur;
        }

        public override Guid Create(Hearing o)
        {
            o.DateEnd = o.Date.AddMinutes(o.Duration);
            base.Create(o);
            SendAlerts(o);
            return o.Id;
        }

        public override void Save(Hearing o)
        {
            o.DateEnd = o.Date.AddMinutes(o.Duration);
            base.Save(o);
            SendAlerts(o);
        }

        private void SendAlerts(Hearing o)
        {
            var a = new Alert {HearingId = o.Id, Title = "Judge sets the date of the hearing", Message = "aa"};
            ur.Insert(a);
            ur.Save();
            if(o.Users != null)
            foreach (var au in o.Users.Select(user => new AlertUser {Alert = a, User = user}))
            {
                ur.Insert(au);
            }
            ur.Save();
        }
    }
}